<?php

namespace app\api\model;

use app\api\model\ConfigSystem as Config;
use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords as Income;
use app\api\model\Withdraw;
use app\api\model\ConfigPersonal;
use think\Db;
use think\Cache;
use Vectorface\Whip\Whip;
use think\Request;
use app\service\Commission;
use app\service\UserLevel;

class User extends Common
{
    static public function rewardbak($user_id, $money, $msg, $channel)
    {
        $id = $user_id;

        $config = Config::index(['in', ['invite', 'fencheng']]);
        $entertainment = -1;
        for ($i = 1; $i <= 3; $i++) {

            $user = self::get($id);

            if ($user && $user->yqr) {
                if ($entertainment == -1) {
                    $entertainment = $user['entertainment'];
                }
                $parent = self::get(['yqm' => $user->yqr]);
                if ($parent['delete_time'] > 0 || $parent['is_banned'] && strtotime($parent['banned_end_time']) > time()) {
                    return false;
                }

                //if ($parent && !$parent['proxy']) {
                if ($parent) {
                    if ($entertainment == 1) {
                        $config['shouyi_' . $i] = $config['shouyi_' . $i] + $config['share_parent_topup_add_fenchen'] > 0 ? $config['shouyi_' . $i] + $config['share_parent_topup_add_fenchen'] : $config['shouyi_' . $i];
                    }
                    if ($user['level'] == 3 && $parent['level'] == 3 && $i == 2) {
                        $income = ($config['shouyi_' . $i] + $config['shouyi_team_hehuo']) * $money;
                    } else {
                        $income = $config['shouyi_' . $i] * $money;
                    }

                    if ($income) {
                        if ($i == 1) {
                            switch ($channel) {
                                case 'topup':
                                    $types = 2;
                                    break;
                                default:
                                    $types = 0;
                                    break;
                            }


                            if (in_array($types, [2])) {
                                $yqms = [];

                                $team = [$parent['yqm']];
                                for ($m = 1; $m <= 2; $m++) {
                                    $chids = self::where(['yqr' => ['in', $team]])->column('yqm');

                                    if ($chids) {
                                        $yqms = array_merge($yqms, $chids);

                                        $team = $chids;
                                    } else {
                                        $m = 4;
                                    }
                                }

                                if ($yqms) {
                                    $ids = self::where(['yqm' => ['in', $yqms]])->column('id');

                                    if ($ids) {
                                        if ($config['shouyi_limit_switch'] && strtotime($config['shouyi_limit_time']) <= strtotime($user['register_datetime'])) {
                                            $income = ($types == 1 ? $config['shouyi_female_1_max'] : $config['shouyi_1_max']) * $money;
                            
                                            if ($income) {
                                                $remark = $msg . '1级 奖励';
                                                Income::index($parent->id, $id, $income, $remark, 1);
                                            }
                                        } else {
                                            $risen = Db::name('config_invite_risen')->where(['user_id'=>$parent->id])->value('value');
                                            $risen = $risen ?? 0;

                                            $user_Level = $config['shouyi_team_'.$parent['level']]??0;


                                            $income = ($config['shouyi_' . $i] + $user_Level + $risen / 100) * $money;

                                            if ($income) {
                                                $remark = $msg . ' 奖励';
                                                Income::index($parent->id, $id, $income, $remark, 1);
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            $remark = $msg . ' 平级奖励';

                            Income::index($parent->id, $id, $income, $remark, 1);
                        }
                    }
                } else {
                    $i = 4;
                    continue;
                }
            } else {
                $i = 4;
                continue;
            }

            $id = $parent->id;
        }
    }

    public static function reward($user_id, $money, $msg, $channel)
    {
        $id = $user_id;
        $config = Config::index(['in', ['invite', 'fencheng']]);

        $childHasSuper = 0;
        $childHasYunying = 0;
        $childHasHehuo = 0;

        for ($i = 1; $i <= 10; $i++) {
            $user = self::get($id);
            if ($user && $user->yqr) {

                // 标记团队链存在的等级
                if ($user['level'] == 1) $childHasSuper = 1;
                if ($user['level'] == 2) $childHasYunying = 1;
                if ($user['level'] == 3) $childHasHehuo = 1;

                $parent = self::get(['yqm' => $user->yqr]);
                if (!$parent || $parent['delete_time'] > 0 || ($parent['is_banned'] && strtotime($parent['banned_end_time']) > time())) {
                    break;
                }
                $topup_commission = $config['shouyi_1'] * $money;
                $team_rate = $config['shouyi_team_'.$parent['level']]??0;

                if ($childHasSuper) {
                    $team_rate -= $config['shouyi_team_1'];
                }
                if ($childHasYunying && $parent['level'] > 2) {
                    $team_rate -= $config['shouyi_team_1'];
                }
                $team_commission = $team_rate * $money;
                $levelText = '';
                if ($childHasHehuo && !$user->team_out) {
                    $commission = ($topup_commission + $team_commission) * $config['shouyi_team_hehuo'];
                    $levelText = '平级';
                } else {
                    if ($i == 1) {
                        $commission = $topup_commission + $team_commission;
                    } else if ($user->team_out) {
                        break;
                    } else {
                        $commission = $team_commission;
                        $levelText = '团队';
                    }
                }

                $remark = $msg . " " . $levelText. "奖励";
                Income::index($parent->id, $id, $commission, $remark, 1, '', 0, 0, 0, $user_id);
            } else {
                break;
            }
            $id = $parent->id;
        }
    }

    static public function femaleRewardbak($user_id, $money, $msg, $channel, $number, $update, $show_money)
    {
        $id = $user_id;

        $config = Config::index(['in', ['invite', 'fencheng']]);
        $entertainment = -1;

        for ($i = 1; $i <= 3; $i++) {

            $user = self::get($id);

            if ($user && $user->yqr) {
                if ($entertainment == -1) {
                    $entertainment = $user['entertainment'];
                }
                $parent = self::get(['yqm' => $user->yqr]);
                if ($parent['delete_time'] > 0 || $parent['is_banned'] && strtotime($parent['banned_end_time']) > time()) {
                    return false;
                }

                //if ($parent && !$parent['proxy']) {
                if ($parent) {
                    if ($i == 1) {
                        switch ($channel) {
                            case 'topup':
                                $types = 2;
                                break;
                            case 'chat':
                            case 'gift':
                            case 'video':
                                $types = 1;
                                break;
                            case 'mall':
                                $types = 3;
                                break;
                            case 'service':
                                $types = 4;
                                break;
                            default:
                                $types = 0;
                                break;
                        }

                        if (in_array($types, [1, 2])) {
                            $yqms = [];

                            $team = [$parent['yqm']];
                            for ($m = 1; $m <= 2; $m++) {
                                $chids = self::where(['yqr' => ['in', $team]])->column('yqm');

                                if ($chids) {
                                    $yqms = array_merge($yqms, $chids);

                                    $team = $chids;
                                } else {
                                    $m = 4;
                                }
                            }

                            if ($yqms) {
                                $ids = self::where(['yqm' => ['in', $yqms]])->column('id');

                                if ($ids) {
                                    if ($config['shouyi_limit_switch'] && strtotime($config['shouyi_limit_time']) <= strtotime($user['register_datetime'])) {
                                        $show_income = $income = ($types == 1 ? $config['shouyi_female_1_max'] : $config['shouyi_1_max']) * $money;
                                        if ($income) {
                                            if ($show_money) {
                                                $show_income = floor(($types == 1 ? $config['shouyi_female_1_max'] : $config['shouyi_1_max']) * $show_money * 100) / 100;
                                            }
                                            $remark = $msg . '1级 奖励';
                                            Income::index($parent->id, $id, $income, $remark, 1, $number, 0, $update, $show_money);
                                        }
                                    } else {
                                        $risen = Db::name('config_invite_risen')->where(['user_id'=>$parent->id])->value('value');
                                        $risen = $risen ?? 0;

                                        $user_Level = $config['shouyi_chat_' . $parent->level]??0;

                                        $show_income = $income = ($config['shouyi_female_' . $i] + $user_Level + $risen / 100) * $money;
                                        if ($income) {
                                            if ($show_money) {
                                                $show_income = floor(($config['shouyi_female_' . $i] + $user_Level + $risen / 100) * $show_money * 100) / 100;
                                            }
                                            $remark = $msg . ' 奖励';
                                            //Income::index($parent->id, $id, $income, $remark, 1);
                                            Income::index($parent->id, $id, $income, $remark, 1, $number, 0, $update, $show_income);
                                        }
                                    }
                                }
                            }
                        } else if($types == 3) {
                            if ($entertainment == 1) {
                                $addShouyi = $config['shouyi_mall_' . $i] + $config['share_add_fencheng_parent_' . $i];
                                $config['shouyi_mall_' . $i] = $addShouyi > 0 ? $addShouyi : $config['shouyi_mall_' . $i];
                            }
                            $income = $config['shouyi_mall_' . $i] * $money;
                            if ($income) {
                                $remark = $msg . ' 1级奖励';
                                Income::index($parent->id, $id, $income, $remark, 1, $number, 0, $update);
                            }
                        } else if($types == 4) {
                            if ($entertainment == 1) {
                                $addShouyi = $config['shouyi_female_' . $i] + $config['share_add_fencheng_parent_' . $i];
                                $config['shouyi_female_' . $i] = $addShouyi > 0 ? $addShouyi : $config['shouyi_female_' . $i];
                            }
                            $income = ($config['shouyi_female_' . $i] - 0.1) * $money;
                            if ($income) {
                                $remark = $msg . ' 1级奖励';
                                Income::index($parent->id, $id, $income, $remark, 1, $number, 0, $update);
                            }
                        }
                    } else {
                        if (in_array($types, [1, 2])) {
                            if($types == 2){
                                if ($entertainment == 1) {
                                    $config['shouyi_' . $i] = $config['shouyi_' . $i] + $config['share_parent_topup_add_fenchen'] > 0 ? $config['shouyi_' . $i] + $config['share_parent_topup_add_fenchen'] : $config['shouyi_' . $i];
                                }
                                $show_income = $income = $config['shouyi_' . $i] * $money;
                                if ($show_money) {
                                    $show_income = floor($config['shouyi_' . $i] * $show_money * 100) / 100;
                                }
                            }else{
                                if ($entertainment == 1) {
                                    $config['shouyi_female_' . $i] = $config['shouyi_female_' . $i] + $config['share_add_fencheng_parent_' . $i] > 0 ? $config['shouyi_female_' . $i] + $config['share_add_fencheng_parent_' . $i] : $config['shouyi_female_' . $i];
                                }

                                if ($user->level == 3 && $parent->level == 3 && $i == 2) {
                                    $config['shouyi_female_' . $i] += $config['shouyi_female_hehuo'];
                                }

                                $show_income = $income = $config['shouyi_female_' . $i] * $money;
                                if ($show_money) {
                                    $show_income = floor($config['shouyi_female_' . $i] * $show_money * 100) / 100;
                                }
                            }

                            if ($income) {
                                $remark = $msg . $i . '级奖励';
                                //Income::index($parent->id, $id, $income, $remark, 1);
                                Income::index($parent->id, $id, $income, $remark, 1, $number, 0, $update, $show_income);
                            }
                        } else if ($types == 4) {
                            if ($entertainment == 1) {
                                $addShouyi = $config['shouyi_service_' . $i] + $config['share_add_fencheng_parent_' . $i];
                                $config['shouyi_service_' . $i] = $addShouyi > 0 ? $addShouyi : $config['shouyi_service_' . $i];
                            }
                            $income = $config['shouyi_service_' . $i] * $money;

                            if ($income) {
                                $remark = $msg . $i . '级奖励';
                                Income::index($parent->id, $id, $income, $remark, 1, $number, 0, $update);
                            }
                        } else{
                            if ($entertainment == 1) {
                                $addShouyi = $config['shouyi_mall_' . $i] + $config['share_add_fencheng_parent_' . $i];
                                $config['shouyi_mall_' . $i] = $addShouyi > 0 ? $addShouyi : $config['shouyi_mall_' . $i];
                            }
                            $income = $config['shouyi_mall_' . $i] * $money;
                            if ($income) {
                                $remark = $msg . $i . '级奖励';
                                Income::index($parent->id, $id, $income, $remark, 1, $number, 0, $update);
                            }
                        }
                    }
                } else {
                    $i = 4;
                    continue;
                }
            } else {
                $i = 4;
                continue;
            }

            $id = $parent->id;
        }
    }

    static public function femaleReward($user_id, $money, $msg, $channel, $number, $update, $show_money, $source_uid = 0)
    {
        $id = $user_id;

        $config = Config::index(['in', ['invite', 'fencheng']]);

        $childHasSuper = 0;
        $childHasYunying = 0;
        $childHasHehuo = 0;

        for ($i = 1; $i <= 10; $i++) {

            $user = self::get($id);

            if ($user && $user->yqr && !$user->team_out) {
                // 标记团队链存在的等级
                if ($user['level'] == 1) $childHasSuper = 1;
                if ($user['level'] == 2) $childHasYunying = 1;
                if ($user['level'] == 3) $childHasHehuo = 1;

                $parent = self::get(['yqm' => $user->yqr]);

                if (!$parent || $parent['delete_time'] > 0 || ($parent['is_banned'] && strtotime($parent['banned_end_time']) > time()) || ($parent->level!=3 && $user->level>=$parent->level)) {
                    break;
                }

                $topup_commission = $config['shouyi_female_1'] * $money;
                $team_rate = $config['shouyi_chat_'.$parent['level']]??0;

                if ($childHasSuper) {
                    $team_rate -= $config['shouyi_chat_1'];
                }
                if ($childHasYunying && $parent['level'] > 2) {
                    $team_rate -= $config['shouyi_chat_1'];
                }
                $team_commission = $team_rate * $money;
                $levelText = '';
                if ($childHasHehuo) {
                    $commission = ($topup_commission + $team_commission) * $config['shouyi_female_hehuo'];
                    $levelText = '平级';
                } else {
                    if ($i == 1) {
                        $commission = $topup_commission + $team_commission;
                    } else {
                        $commission = $team_commission;
                        $levelText = '团队';
                    }
                }

                $remark = $msg . " " . $levelText. "奖励";
                Income::index($parent->id, $id, $commission, $remark, 1, $number, 0, $update, 0, $source_uid);
            } else {
                break;
            }

            $id = $parent->id;
        }
    }

    static public function fenchengbak($user_id, $to_user, $money, $channel, $content = '', $order = '', $update = 0)
    {
        $config = Config::index('fencheng');
        $user = self::get($user_id);

        $fencheng_user = $user['fencheng_user'] + 0 ?: $config['fencheng_user'];
        if ($user['entertainment'] == 1) {
            if ($fencheng_user + $config['share_add_fencheng'] > 0) {
                $fencheng_user = $fencheng_user + $config['share_add_fencheng'];
            }
        }
        switch ($channel) {
            case 'vip':
                $msg = '购买VIP';
                //$config['fencheng_user'] = 1;
                $fencheng_user = 1;
                break;
            case 'topup':
                $msg = '充值';
                //$config['fencheng_user'] = 1;
                $fencheng_user = 1;
                break;
            case 'chat':
                $msg = '聊天';
                break;
            case 'gift':
                $msg = '收获礼物';
                $channel = 'chat';
                break;
            case 'mall':
                $msg = '商品订单结算';
                $channel = 'mall';
                $fencheng_user = 1;
                break;
            case 'service':
                $msg = '服务订单结算';
                $channel = 'service';
                $fencheng_user = 1;
                break;
        }

        if ($money + 0) {
            $number = $order ?: uniqid();

            if ($fencheng_user + 0) {

                $fencheng = $show_fencheng = $money * $fencheng_user;
                if ($to_user) {

                    // if ($user['score'] > 99 && $show_fencheng) {
                    //     $fencheng = $money * 0.54;
                    // }
                    $remark = $content ?: $msg;
                    $remark .= '收益';

                    Income::index($user_id, $to_user, $fencheng, $remark, 1, $number, 0, $update, $show_fencheng);
                }

                $fencheng_proxy_rate = 0;

                if ($user['yqr']) {
                    $parent = self::get(['yqm' => $user['yqr']]);

                    if ($parent) {
                        /*if ($parent['proxy']) {
                            if (($parent['fencheng_' . $channel] + 0)) {
                                $fencheng_proxy = $money * $fencheng_user * $parent['fencheng_' . $channel];
                                $fencheng_proxy_rate = $parent['fencheng_' . $channel];
        
                                if ($parent->admin) {
                                    $proxy_prev = self::get($parent->admin);
            
                                    if ($proxy_prev) {
                                        $fencheng_prev = $fencheng_proxy * $parent['fencheng_prev'];
                
                                        if ($fencheng_prev + 0) {
                                            $remark = $msg . '上级代理收益分成';
                    
                                            Income::index($proxy_prev->id, $parent->id, $fencheng_prev, $remark, 1, $number,0,$update);
                                        }
                                    }
                                }
        
                                $fencheng_proxy = $fencheng_proxy * (1 - $parent['fencheng_prev']);
        
                                $remark = $msg . '代理收益';
        
                                Income::index($parent->id, $user_id, $fencheng_proxy, $remark, 1, $number,0,$update);
                            }
                        } else {
                            if ($user['sex'] == '女') {
                                self::femaleReward($user_id, $money * $fencheng_user, $msg);
                            }
                        }*/

                        if ($user['sex'] == '女' || $channel == 'mall' || $channel == 'service') {
                            $msg = $content ?: $msg;
                            $msg = Privatechat::changeWord($msg);

                            self::femaleReward($user_id, $fencheng, $user['name'] . "(".$user_id.") " . $msg, $channel, $number, $update, $show_fencheng);
                            //self::femaleReward($user_id, $money * $fencheng_user, $msg, $channel);
                        }
                    }
                }
            }
        }
    }
    static public function fencheng($user_id, $to_user, $money, $channel, $content = '', $order = '', $update = 0)
    {
        $config = Config::index('fencheng');
        $user = self::get($user_id);

        $fencheng_user = $user['fencheng_user'] + 0 ?: $config['fencheng_user'];
        switch ($channel) {
            case 'vip':
                $msg = '购买VIP';
                $fencheng_user = 1;
                break;
            case 'topup':
                $msg = '充值';
                $fencheng_user = 1;
                break;
            default:
                break;
        }

        if ($money + 0) {
            $number = $order ?: uniqid();

            if ($fencheng_user + 0) {

                $fencheng = $show_fencheng = $money * $fencheng_user;
                if ($to_user) {
                    $remark = $content ?: $msg;
                    $remark .= '收益';

                    Income::index($user_id, $to_user, $fencheng, $remark, 1, $number, 0, $update, $show_fencheng, $to_user);
                }

                if ($user['yqr'] && !$user['team_out']) {
                    $parent = self::get(['yqm' => $user['yqr']]);

                    if ($parent) {
                        if ($user['sex'] == '女' || $channel == 'mall' || $channel == 'service') {
                            $msg = $content ?: $msg;
                            $msg = Privatechat::changeWord($msg);

                            self::femaleReward($user_id, $fencheng, $user['name'] . "(".$user_id.") " . $msg, $channel, $number, $update, $show_fencheng, $to_user);
                        }
                    }
                }
            }
        }
    }

    static public function rewardHunjie($user_id, $money, $field, $content, $order_id='')
    {
        $id = $user_id;

        $config = Config::index(['in', ['invite', 'hunjie']]);

        $company_rate = 1 - $config[$field . 1] - $config[$field . 2] - $config[$field . 3];

        $company = 1;

        $ids = [];
        for ($i = 1; $i <= 3; $i++) {

            $user = self::get($id);

            if ($user) {
                $parent = self::get(['yqm' => $user->yqr]);

                if ($parent) {
                    $profile = Db::name('user_profile')->where(['user_id'=>$parent['id']])->find();
                    if ($profile && $profile['proxy']) {

                        $rate = $config[$field . $i];

                        if ($field == 'pullline_shouyi_' && $profile['partner']) {
                            $partnerConfig = Db::name('hunjie_partner')->where(['type' => $profile['partner']])->find();
                            if ($partnerConfig->pullline + 0) {
                                $rate = $partnerConfig->pullline;
                            }
                        }

                        if ($company) {
                            $company -= $rate;
                        }

                        $income = $rate * $money;

                        if ($income) {
                            $remark = $content . $i . '级奖励';

                            Income::index($parent->id, $user_id, $income, $remark, 1);
                        }
                    }
                } else {
                    $i = 4;
                    continue;
                }
            } else {
                $i = 4;
                continue;
            }

            $id = $parent->id;
        }
    }

    static public function changeIntimate($userid, $touserid, $money, $remark, $orderid = '', $reward = 1, $update = 1, $channel = 'chat', $score = 0, $female = 0)
    {
        if ($userid < $touserid) {
            $field_count = 'count_a';
            $couple_a = $userid . ',' . $touserid;
            $couple_b = $touserid . ',' . $userid;
        } else {
            $field_count = 'count_b';
            $couple_a = $touserid . ',' . $userid;
            $couple_b = $userid . ',' . $touserid;
        }

        $intimate = UserIntimate::get(['couple_a' => $couple_a]);
        if ($intimate) {
            UserIntimate::update([
                'id' => $intimate['id'],
                $field_count => $intimate[$field_count] + $money,
                'intimate' => $intimate['intimate'] + $money * 1,
                'update_time' => time(),
                'unshow'=>0
            ]);
        } else {
            UserIntimate::create([
                'couple_a' => $couple_a,
                'couple_b' => $couple_b,
                $field_count => $money,
                'intimate' => $money * 1,
                'create_time' => time(),
                'update_time' => time()
            ]);
        }

        if (!$female) {
            self::where(['id' => $touserid])->setInc('charm_value', $money * 1);

            /*$intimate = UserIntimate::get(['couple_a' => $couple_a]);
    
            $userDefend = UserDefend::get(['user_id' => $userid, 'to_user' => $touserid]);*/

            $touserInfo = self::get($touserid);

            /*$types = $touserInfo['sex'] == '女' ? 2 : 1;
            $gradeCharm = GradeCharm::where(['types' => $types, 'min' => ['elt', $touserInfo['charm_value']]])->order('grade desc')->value('grade');
    
            $config = Config::index('defend');
    
            if ($touserInfo['sex'] == '女') {
                $gift_money = $gradeCharm * $config['female_times'];
                if ($gift_money < $config['female_min']) {
                    $gift_money = $config['female_min'];
                }
            } else {
                $gift_money = $gradeCharm * $config['male_times'];
                if ($gift_money < $config['male_min']) {
                    $gift_money = $config['male_min'];
                }
            }*/

            /*if (!$touserInfo['angel']) {
        
                $hadMoney = $userid < $touserid ? $intimate['count_a'] : $intimate['count_b'];
        
                $mustMoney = $gift_money - ($hadMoney - $money);
        
                $isAngel = 0;
                if ($mustMoney <= $money) {
                    $isAngel = 1;
                } else {
                    $gradeDefend = GradeDefend::where(['min' => ['elt', $hadMoney]])->order('grade desc')->find();
            
                    if ($gradeDefend) {
                        $isAngel = 1;
                    }
                }
        
                if ($isAngel) {
                    self::update(['id' => $touserid, 'angel' => $userid]);
                    UserDefend::where(['user_id' => ['neq', $userid], 'to_user' => $touserid])->update(['angel' => 0, 'update_time' => time()]);
            
                    $isAngel = 1;
                    $update_time = time();
            
                    // 任务
                    Task::finish('defend', $userid);
                } else {
                    $isAngel = 0;
                    $update_time = $userDefend ? $userDefend['update_time'] : time();
                }
        
                $defend_money = $hadMoney;
            } else {
                $angel = UserDefend::get(['to_user' => $touserid, 'angel' => 1]);
        
                if ($userDefend) {
                    $defend_money_new = $userDefend['money'] + $money;
                } else {
                    $defend_money_new = $money;
                }
        
                if (($angel['money'] < $defend_money_new) && $angel['user_id'] != $userid && $gift_money <= $defend_money_new) {
                    self::update(['id' => $touserid, 'angel' => $userid]);
                    UserDefend::where(['user_id' => ['neq', $userid], 'to_user' => $touserid])->update(['angel' => 0, 'update_time' => time()]);
            
                    $isAngel = 1;
                    $update_time = time();
            
                    // 任务
                    Task::finish('defend', $userid);
                } else {
                    $isAngel = 0;
                    $update_time = $angel['update_time'];
                }
        
                $defend_money = $defend_money_new;
            }
    
            if ($userDefend) {
                UserDefend::update([
                    'id' => $userDefend['id'],
                    'angel' => $isAngel,
                    'money' => $defend_money,
                    'update_time' => $update_time
                ]);
            } else {
                UserDefend::create([
                    'user_id' => $userid,
                    'to_user' => $touserid,
                    'money' => $defend_money,
                    'angel' => $isAngel,
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
            }*/
        }

        if ($reward) {
            if (!$female) {
                $money = $touserInfo['sex'] == '女' ? $score : $money;

                self::fencheng($touserid, $userid, $money * 1, $channel, $remark, $orderid, $update);
            } else {
                self::fencheng($userid, $touserid, $money * 1, $channel, $remark, $orderid, $update);
            }
        }
    }

    static public function checkLogin($user_id)
    {
        $return = changeCode(config('code'));

        if (!$user_id) {
            return $return['user.error.expired'];
        }

        $member = _user($user_id);

        if ($member) {
            // if (!$member['reg']) {
            //     return $return['user.error.undone'];
            // } else 
            // if ($member['is_banned'] && strtotime($member['banned_end_time']) > time()) {
            //     return $return['user.error.blockade'];
            // }
        } else {
            return $return['user.error.notExist'];
        }

        return json(['code' => 200, 'user' => $member]);
    }

    /** 绑定上级 */
    static public function bindPrev($user)
    {
        if (!$user['yqr']) {
            $whip = new Whip();
            $clientAddress = $whip->getValidIpAddress();

            $record = ProxyVisitRecords::get(['ip' => $clientAddress]);

            if ($record) {
                $prev = User::get($record['user_id']);

                if ($prev && $prev['yqm'] != $user['yqm']) {

                    $next1 = User::where(['yqr'=>$user['yqm']])->column('yqm');
                    if(sizeof($next1)){
                        $next2 = User::where(['yqr'=>['in', $next1]])->column('yqm');
                        $next = array_merge($next1, $next2);
                        if(in_array($prev->yqm, $next)){
                            return false;
                        }
                    }

                    User::update(['id' => $user['id'], 'yqr' => $prev->yqm]);
                    User::bindParentWalfare($prev->id, $user['id'], $user['device_id']);
                }
            }
        }
    }

    /** 生成唯一邀请码 */
    static public function createInviteCode($number = 4)
    {
        $count = 0;
        for ($m = 0; $m < 1; $m++) {
            $contain = [];
            for ($i = 0; $i < 50; $i++) {
                $rand_code = mt_rand(1, pow(10, $number));

                if (in_array($rand_code, $contain)) {
                    $i--;
                } else {
                    $contain[] = $rand_code;
                }
            }

            $had_invite_code = (new User)->where(['yqm' => ['in', $contain]])->column('yqm');

            $contain = array_diff($contain, $had_invite_code);

            if (isset($contain[0])) {
                return $contain[0];
            } else {
                $m = -1;
                $count++;
                if ($count > 5) {
                    $number++;
                }
            }
        }
    }


    static public function setUnion($user_id, $opneid, $unionid = '')
    {
        if(!$unionid){
            return;
        }

        $bind = WechatUnion::get($user_id);
        if($bind){
            if($bind->unionid){
                return;
            }
            $bind->unionid = $unionid;
            $bind->save();
        }else{
            WechatUnion::create([
                'user_id'=>$user_id,
                'wxapp_openid'=>$opneid,
                'unionid'=>$unionid,
            ]);
        }
    }


    public static function welfare($user)
    {
        // self::rechargeWelfare($user);
        // return false;
        if($user['sex'] <> '女' || $user['score'] > 5 || $user['reg'] == 0){
            return;
        }
        $config = Config::index('welfare');
        if(!isset($config['welfare_score']) || $config['welfare_score'] <= 0){
            return;
        }

        $withdraw = Withdraw::where(['userid'=>$user['id']])->find();
        if($withdraw){
            return;
        }
        $welfare = Db::name('welfare')->master()->where(['user_id'=>$user['id']])->find();
        if($welfare){
            return;
        }
        $welfareScore = $config['welfare_score'];
        $welfareRequireInteract = $config['welfare_score_interact'];
        $time = time();
        $frozen = Db::name('wallet_frozen')->where(['user_id'=>$user['id']])->find();
        if($frozen){
            Db::name('wallet_frozen')->where(['id'=>$frozen['id']])->setInc('value', $welfareScore);
        }else{
            Db::name('wallet_frozen')->insert(['user_id'=>$user['id'], 'value'=>$welfareScore, 'create_time'=>$time, 'update_time'=>$time]);
        }
        Db::name('welfare')->insert(['user_id'=>$user['id'], 'value'=>$welfareScore, 'interact'=>$welfareRequireInteract, 'time'=>$time]);
        Db::name('wallet_frozen_records')->insert(['user_id'=>$user['id'], 'value'=>$welfareScore, 'time'=>$time, 'remark'=>'系统赠送积分(新用户福利)']);

        // User::where(['id'=>$user['id']])->setInc('score', $welfareScore);
        $remark = '系统赠送积分(新用户福利)';
        Income::index($user['id'], 0, $welfareScore, $remark, 1);

        Privatechat::notice($user['id'], $config['welfare_score_tip']);
    }
    public static function regNotice($user)
    {
        $configs = Config::index('reg');
        foreach ($configs as $key => $value) {
            if (stripos($key, 'reg_female_msg_') !== false && $user['sex'] == '女' && $value) {
                Privatechat::notice($user['id'], $value, '', 0, stripos($value, 'disk/uploads/image') !== false ? 1 : 0);
            }
        }
    }

    // 推送到打招呼/未回复
    public static function pushchat($user, $test = false)
    {
        return false;
        // if ($user['sex'] == '女') {
            // if (strtotime($user['register_datetime']) < strtotime('2022-09-01')) {
            //     return;
            // }
        // } else 
        if ($user['age'] < 18) {
            return;
        } else {
            // if (strtotime($user['register_datetime']) < strtotime('2022-10-01')) {
            //     return;
            // }
            if ($user['sex'] == '男' && strtotime($user['register_datetime']) > strtotime(date('Y-m-d'))) {
                return;
            }
        }
        if ($user['entertainment'] == 1) {
            return;
        }
        $UserData = UserData::get(['user_id' => $user['id']]);
        if ($UserData['topup'] > 20000) {
            return;
        }
        $data = ConfigPersonal::get(['user_id' => $user['id']]);
        if ($data['fate_switch'] == 0) {
            return;
        }
        $config = Db::name('config_system')->where(['category' => 'kefu'])->column('title, content');
        $kefu = (int)strip_tags($config['id']);
        if ($kefu == $user['id']) {
            return;
        }

        $notin = [$kefu];

        $hasChatlista = Db::name('chat_lists')->where(['user_id'=>$user['id']])->column('another_id');
        $hasChatlistb = Db::name('chat_lists')->where(['another_id'=>$user['id']])->column('user_id');

        $notin = array_merge($notin, $hasChatlistb, $hasChatlista);

        $field = 'CASE WHEN a.shouyi>0 && a.shouyi<500 THEN 1 WHEN a.shouyi>=500 && a.shouyi<1000 THEN 4 WHEN a.shouyi>=1000 && a.shouyi<5000 THEN 3 WHEN a.shouyi>=5000 && a.shouyi<10000 THEN 2 ELSE 0 END AS shouyi';
        if ($user['sex'] == '女') {
            $field = 'CASE WHEN a.volley>0 && a.volley<50 THEN 1 WHEN a.volley>=50 && a.volley<100 THEN 4 WHEN a.volley>=100 && a.volley<500 THEN 3 WHEN a.volley>=500 && a.volley<1000 THEN 2 ELSE 0 END AS shouyi';
        }
        if ($user['sex'] == '男') {
            $females = Db::name('user a')->join('user_data b', 'a.id=b.user_id', 'left')->field('a.id, ' . $field)
            ->where([
                'a.id' => ['not in', $notin],
                'a.sex' => '女',
                'a.age' => ['between', [18, $user['age']]],
                'a.is_banned' => 0,
                'a.is_online' => 1,
                'a.entertainment' => $user['entertainment'],
                'a.real_avatar' => $data['fate_realavatar_limit'] ? 1 : ['in', '0,1'],
                'a.realname_auth' => $data['fate_realname_limit'] ? 2 : ['in', '0,1,2,3'],
                'b.topup' => ['<=', 20000]
            ])
            ->order('shouyi desc')->limit(rand(5, 7))->select();
        } else {
            $females = Db::name('user a')->join('user_data b', 'a.id=b.user_id', 'left')->field('a.id, ' . $field)
            ->where([
                'a.id' => ['not in', $notin],
                'a.sex' => '男',
                'a.age' => ['between', [$user['age'], 999]],
                'a.is_banned' => 0,
                'a.is_online' => 1,
                'a.entertainment' => $user['entertainment'],
                'a.real_avatar' => $data['fate_realavatar_limit'] ? 1 : ['in', '0,1'],
                'a.realname_auth' => $data['fate_realname_limit'] ? 2 : ['in', '0,1,2,3'],
                'b.topup' => ['<=', 20000]
            ])
            ->whereTime('register_datetime', '<', date('Y-m-d'))
            ->order('shouyi desc')->limit(rand(5, 7))->select();
        }
        
        if ($test) {
            return $females;
        }

        $contents = Db::name('privatechat_zhaohu')->where(['types' => 2, 'is_hidden' => 0])->cache(86400)->column('content');
        $url = 'http://' . getenv('APP_URL') . '/apis/home/privatechat/addtalk';
        foreach ($females as $key => $value) {
            $rand = mt_rand(0, count($contents) - 1);
            $data = [
                'userid' => $user['sex'] == '男' ? $value['id'] : $user['id'],
                'touserid' => $user['sex'] == '男' ? $user['id'] : $value['id'],
                'content' => $contents[$rand],
                'timing' => 1,
                'greet' => 1,
                'single' => $user['sex'] == '男' ? 1 : 0,
                'fate' => 1,
            ];

            sendcurl($url, json_encode($data, JSON_UNESCAPED_UNICODE));
        }

        cache('onlineGreet:' . $user['id'], time(), 3600);
    }

    // 推送到聊天列表
    // test 测试
    // uidNotIn 包含其他notin
    public static function pushchatUnFirst($user, $test = false, $uidNotIn = true)
    {
        // return false;
        if(!$test && Cache::store('redis')->get('pushchatUnFirst:' . $user['id'])){
            return false;
        }
        Cache::store('redis')->set('pushchatUnFirst:' . $user['id'], time(), 20);
        if(strpos($user['city'],'市') !== false) {
            $user['city'] = substr($user['city'],0,strrpos($user['city'],'市'));
        }

        if ($user['age'] < 18 || !in_array($user['entertainment'], ['0','2','3'])) {
            return;
        }
        $UserData = UserData::get(['user_id' => $user['id']]);
        if ($UserData['topup'] > 20000) {
            return;
        }
        $data = ConfigPersonal::get(['user_id' => $user['id']]);
        if ($data['fate_switch'] == 0) {
            return;
        }
        if (!$data) {
            $data = ['fate_realavatar_limit' => 0, 'fate_realname_limit' => 0];
        }
        $res = false;
        switch ($user['sex']) {
            case '男':
                // if (strtotime($user['register_datetime']) > strtotime(date('Y-m-d'))) {
                //     return;
                // }
                $res = self::pushchatUnFirstMale($user, $data, $test, true, $uidNotIn);
                break;
            
            default:
                // if ($user['realname_auth'] == 0) {
                //     return;
                // }
                $res = self::pushchatUnFirstFemale($user, $data, $test, true, $uidNotIn);
                break;
        }
        if ($test) {
            return $res;
        }
        if ($res) {
            $cacheTime = 7200;
            if ($user['quality'] == 4) {
                $cacheTime = 1800;
            } else if ($user['quality'] == 3) {
                $cacheTime = 3600;
            }
            if ($user['quality'] == 4) {
                if ($user['nation']) {
                    $cacheTime = $cacheTime / 2;
                } else {
                    $isSelectUser = Db::name('select_users')->where(['user_id'=>$user['id']])->find();
                    if ($isSelectUser) {
                        $cacheTime = $cacheTime / 2;
                    }
                }
            }
            Cache::store('redis')->set('pushchatUnFirst:' . $user['id'], $res, $cacheTime);
            self::pushChatUserCache($user['sex'], $res);
            // cache('pushchatUnFirst:' . $user['id'], time(), 3600);
        } else if ($user['quality'] > 1) {
            $hiEmptyCacheKey = 'hiEmpty:'.$user['id'];
            if (!cache($hiEmptyCacheKey)) {
                Db::name('system_hi_chat_empty')->insert(['user_id'=>$user['id'], 'time'=>time()]);
                cache($hiEmptyCacheKey, 1, 1800);
            }
        }
    }

    private static function pushChatUserCache($sex = '', $uid = 0)
    {
        $cachekey = 'pushChatUser'.$sex;
        $data = Cache::store('redisUnclear')->get($cachekey);
        $data = $data ? json_decode($data, true) : [];
        $timenow = time();

        $datas = $data;
        foreach ($data as $key => $value) {
            if ($value['exp'] > $timenow) {
                break;
            }
            unset($datas[$key]);
        }
        $uids = array_column($datas, 'id');

        if ($uid && !in_array($uid, $uids)) {
            $datas[] = ['id'=>$uid, 'exp'=>$timenow+20*60];
            $uids[] = $uid;
        }
        $exp = array_column($datas, 'exp');
        array_multisort($exp, SORT_ASC, $datas);
        Cache::store('redisUnclear')->set($cachekey, json_encode($datas), 86400);
        // var_dump($datas);exit;
        return $uids;
    }

    public static function getPornoWhere($porno_lv) {
        $where = [];
        switch ((int)$porno_lv) {
            case 0:
                $where = ['in', [0,1]];
                break;
            case 1:
                $where = ['in', [0,1,2]];
                break;
            case 2:
                $where = ['in', [1,2]];
                break;
            
            default:
                $where = ['>', 1];
                break;
        }
        return $where;
    }
    public static function pushchatUnFirstMale($user, $data = [], $test = false, $shield = true, $uidNotIn = true)
    {
        if ($user['quality'] == 1) {
            return false;
        }
        $config = Db::name('config_system')->where(['category' => 'kefu'])->column('title, content');
        $kefu = (int)strip_tags($config['id']);
        if ($kefu == $user['id']) {
            return false;
        }

        $notin = [$kefu];

        $hasChatlista = Db::name('chat_lists')->where(['user_id'=>$user['id']])->whereTime('user_time', '-30 day')->column('another_id');
        $hasChatlistb = Db::name('chat_lists')->where(['another_id'=>$user['id']])->whereTime('another_time', '-30 day')->column('user_id');
        $blacklist = Blacklist::lists($user['id'], false, true);
        // $userDataMax = Db::name('user_data')->where(['income'=>['>=', 20000]])->cache(1800)->column('user_id');

        $lastPush = [];
        if ($shield) {
            $lastPush = self::pushChatUserCache($user['sex']);
        }

        if ($uidNotIn) {
        $notin = array_merge($notin, $hasChatlistb, $hasChatlista, $blacklist, $lastPush);
        // var_dump($notin);exit;
        $lastOne = Db::name('privatechat')->where(['type'=>0, 'single'=>1])->whereTime('addtime','-1 hours')->column('userid');
        if (sizeof($lastOne)){
            $notin = array_merge($notin, array_unique($lastOne));
        }
        }

        $field = 'CASE WHEN a.city="'.$user['city'].'" THEN 1 ELSE 0 END AS citys';
        $fetchSql = $test;
        $female = Db::name('user a')->field('a.id, ' . $field)->where([
            'a.id' => ['not in', $notin],
            'a.sex' => '女',
            'a.delete_time' => 0,
            'a.age' => ['between', [$user['age'] - 20, $user['age'] + 5]],
            'a.is_banned' => 0,
            'a.is_online' => 1,
            'a.realname_auth' => ['<>', 0],
            // 'a.entertainment' => $user['entertainment'],
            'a.entertainment' => ['in', '0,2'],
            'a.real_avatar' => $data['fate_realavatar_limit'] ? 1 : ['in', '0,1'],
            'a.realname_auth' => $data['fate_realname_limit'] ? 2 : ['in', '0,1,2,3'],
            'a.quality' => ['>', 1],
            // 'a.porno_lv'=>$user['porno_lv']==1||$user['porno_lv']==2?['in',[1,2]]:['<>',1],
            'a.porno_lv'=>self::getPornoWhere($user['porno_lv']),
        ])->join('user_repeat_check c', 'a.id=c.user_id')->where('a.age >= 18 and c.sys_channel=1')->whereNotNull('a.phone')->order('last_login_datetime desc, citys desc, a.quality desc')->fetchSql($fetchSql)->find();
        if ($fetchSql) {
            return $female;
        }
        if ($test) {
            return $female;
        }
        if ($female) {
            $contents = Db::name('privatechat_zhaohu')->where(['types' => 2, 'is_hidden' => 0])->cache('systemzhaohuall',86400)->column('content');
            $url = 'http://' . getenv('APP_URL') . '/apis/home/privatechat/addtalk';
            $rand = mt_rand(0, count($contents) - 1);
            $data = [
                'userid' => $female['id'],
                'touserid' => $user['id'],
                'content' => $contents[$rand],
                'timing' => 1,
                'greet' => 1,
                'single' => 1,
                'notice' => 1,
                'quality'=> 1
            ];

            sendcurl($url, json_encode($data, JSON_UNESCAPED_UNICODE));
            return $female['id'];
        } else if (sizeof($lastPush)){
            return self::pushchatUnFirstMale($user, $data, $test, false);
        }
        return false;
    }
    public static function pushchatUnFirstFemale($user, $data, $test = false, $shield = true, $uidNotIn = true)
    {
        if ($user['quality'] < 2) {
            return false;
        }
        $config = Db::name('config_system')->where(['category' => 'kefu'])->column('title, content');
        $kefu = (int)strip_tags($config['id']);
        if ($kefu == $user['id']) {
            return false;
        }

        $notin = [$kefu];

        if ($uidNotIn) {
        $hasChatlista = Db::name('chat_lists')->where(['user_id'=>$user['id']])->whereTime('user_time', '-30 day')->column('another_id');
        $hasChatlistb = Db::name('chat_lists')->where(['another_id'=>$user['id']])->whereTime('another_time', '-30 day')->column('user_id');
        $blacklist = Blacklist::lists($user['id'], false, true);
        $userDataMax = Db::name('user_data')->where(['topup'=>['>=', 20000]])->cache(1800)->column('user_id');

        $lastPush = [];
        if ($shield) {
            $lastPush = self::pushChatUserCache($user['sex']);
        }

        $notin = array_merge($notin, $hasChatlistb, $hasChatlista, $blacklist, $lastPush, $userDataMax);
        }

        $field = '';
        $order = '';
        $male = false;
        $fetchSql = $test;
        if ($user['quality'] == 4) {
            $field = 'CASE WHEN a.activeval>0 && a.activeval<50 THEN 1
                            WHEN a.activeval>=50 && a.activeval<100 THEN 3
                            WHEN a.activeval>=100 && a.activeval<300 THEN 4
                            WHEN a.activeval>=300 && a.activeval<600 THEN 2
                            ELSE 0 END AS activeval,CASE WHEN a.city="'.$user['city'].'" THEN 1 ELSE 0 END AS citys';
            $order = 'last_login_datetime desc, citys desc, activeval desc, volley desc';
            $male = Db::name('user')
                        ->alias('a')
                        ->join('user_repeat_check c', 'a.id=c.user_id')
                        ->field('a.id, ' . $field)
                        ->where([
                            'a.id' => ['not in', $notin],
                            'a.sex' => '男',
                            'a.age' => ['between', [$user['age'] - 5, $user['age'] + 20]],
                            'a.is_banned' => 0,
                            'a.is_online' => 1,
                            // 'a.entertainment' => $user['entertainment'],
                            'a.entertainment' => ['in', '0,2'],
                            'a.real_avatar' => $data['fate_realavatar_limit'] ? 1 : ['in', '0,1'],
                            'a.realname_auth' => $data['fate_realname_limit'] ? 2 : ['in', '0,1,2,3'],
                            'a.quality' => ['>', 1],
                            // 'a.porno_lv'=>$user['porno_lv']==1||$user['porno_lv']==2?['in',[1,2]]:['<>',1],
                            'a.porno_lv'=>self::getPornoWhere($user['porno_lv']),
                            'c.sys_channel'=>1
                        ])
                        ->where('a.age >= 18')
                        // ->whereTime('a.register_datetime', '<', date('Y-m-d'))
                        ->order($order)
                        ->fetchSql($fetchSql)
                        ->find();
        } else if ($user['quality'] == 3) {
            $overtopup = Db::name('topup')->where(['state'=>1])->group('fk_userid')->field('fk_userid,sum(price) total')->order('total desc')->buildSql();
            $fk_userids = Db::table($overtopup.' a')
                ->where('a.total','>',200)
                ->order('total','desc')
                ->fetchSql(false)
                ->cache(3600)
                ->column('fk_userid');
            $field = 'CASE WHEN activeval>0 && activeval<50 THEN 1
                            WHEN activeval>=50 && activeval<100 THEN 3
                            WHEN activeval>=100 && activeval<300 THEN 4
                            WHEN activeval>=300 && activeval<600 THEN 2
                            ELSE 0 END AS activeval,CASE WHEN city="'.$user['city'].'" THEN 1 ELSE 0 END AS citys';
            $order = 'last_login_datetime desc, citys desc, activeval desc';
            $male = Db::name('user')
                        ->alias('a')
                        ->join('user_repeat_check c', 'a.id=c.user_id')
                        ->field('a.id, ' . $field)
                        ->where([
                            'a.id' => ['in', $fk_userids],
                            'a.id' => ['not in', $notin],
                            'a.sex' => '男',
                            'a.age' => ['between', [$user['age'] - 5, $user['age'] + 20]],
                            'a.is_banned' => 0,
                            'a.is_online' => 1,
                            // 'a.entertainment' => $user['entertainment'],
                            'a.entertainment' => ['in', '0,2'],
                            'a.real_avatar' => $data['fate_realavatar_limit'] ? 1 : ['in', '0,1'],
                            'a.realname_auth' => $data['fate_realname_limit'] ? 2 : ['in', '0,1,2,3'],
                            'a.quality' => ['>', 1],
                            // 'a.porno_lv'=>$user['porno_lv']==1||$user['porno_lv']==2?['in',[1,2]]:['<>',1],
                            'a.porno_lv'=>self::getPornoWhere($user['porno_lv']),
                            'c.sys_channel'=>1
                        ])
                        ->where('a.age >= 18')
                        // ->whereTime('a.register_datetime', '<', date('Y-m-d'))
                        ->order($order)
                        ->fetchSql($fetchSql)
                        ->find();
        } else if ($user['quality'] == 2) {
            $overtopup = Db::name('topup')->where(['state'=>1])->group('fk_userid')->field('fk_userid,sum(price) total')->order('total desc')->buildSql();
            $fk_userids = Db::table($overtopup.' a')
                ->where('a.total','<',200)
                ->order('total','desc')
                ->fetchSql(false)
                ->cache(3600)
                ->column('fk_userid');
            $field = 'CASE WHEN city="'.$user['city'].'" THEN 1 ELSE 0 END AS citys';
            $order = 'last_login_datetime desc, citys desc, activeval desc';
            $male = Db::name('user')
                        ->alias('a')
                        ->join('user_repeat_check c', 'a.id=c.user_id')
                        ->field('a.id, ' . $field)
                        ->where([
                            'a.id' => ['in', $fk_userids],
                            'a.id' => ['not in', $notin],
                            'a.sex' => '男',
                            'a.age' => ['between', [$user['age'] - 5, $user['age'] + 20]],
                            'a.is_banned' => 0,
                            'a.is_online' => 1,
                            // 'a.entertainment' => $user['entertainment'],
                            'a.entertainment' => ['in', '0,2'],
                            'a.real_avatar' => $data['fate_realavatar_limit'] ? 1 : ['in', '0,1'],
                            'a.realname_auth' => $data['fate_realname_limit'] ? 2 : ['in', '0,1,2,3'],
                            'a.quality' => ['>', 1],
                            // 'a.porno_lv'=>$user['porno_lv']==1||$user['porno_lv']==2?['in',[1,2]]:['<>',1],
                            'a.porno_lv'=>self::getPornoWhere($user['porno_lv']),
                            'c.sys_channel'=>1
                        ])
                        ->where('a.age >= 18')
                        // ->whereTime('a.register_datetime', '<', date('Y-m-d'))
                        ->order($order)
                        ->fetchSql($fetchSql)
                        ->find();
        }
        if ($fetchSql) {
            return $male;
        }
        if ($test) {
            return $male;
        }

        if ($male) {
            $contents = Db::name('privatechat_zhaohu')->where(['types' => 2, 'is_hidden' => 0])->cache('systemzhaohuall',86400)->column('content');
            //$url = 'http://' . getenv('APP_URL') . '/apis/home/privatechat/addtalk';
            $url = 'http://' . getenv('APP_HOST_LOCAL') . '/apis/home/privatechat/addtalk';
            $rand = mt_rand(0, count($contents) - 1);
            $data = [
                'userid' => $user['id'],
                'touserid' => $male['id'],
                'content' => $contents[$rand],
                'timing' => 1,
                'greet' => 1,
                'single' => $user['realname_auth'] > 0 ? 0 : 2,
                'notice' => 1,
                'quality'=> 1
            ];

            sendcurl($url, json_encode($data, JSON_UNESCAPED_UNICODE));

            return $male['id'];
        } else if (sizeof($lastPush)){
            return self::pushchatUnFirstFemale($user, $data, $test, false);
        }
        return false;
    }

    public static function bindParentWalfare($parent_id, $invited_id, $device_id = '', $ip = '')
    {
        return false;
        $score = 10;
        $hasDevice = Db::name('user_invite_records')->where(['user_id'=>$parent_id, 'device'=>$device_id])->count();
        $hasIP = 0;
        if ($ip) {
            $hasIP = Db::name('user_invite_records')->where(['user_id'=>$parent_id, 'ip'=>$ip])->whereTime('create_time', '-72 hours')->count();
        }
        $limitInvite = Db::name('limit_invite')->where(['user_id'=>$parent_id])->find();

        $state = 1;
        if ($hasDevice || $hasIP || $limitInvite) {
            $score = 0;
        } else {
            // $month = Db::name('user_invite_records')->where(['user_id'=>$parent_id, 'score'=>['>', 0], 'state'=>1])->whereTime('create_time', 'month')->count();
            // if ($month >= 100) {
                $state = 0;
            // } else {
            //     Income::index($parent_id, $invited_id, $score, '邀请奖励', 1);
            // }
        }
        Db::name('user_invite_records')->insert([
            'user_id'=>$parent_id,
            'device'=>$device_id,
            'ip'=>$ip,
            'touserid'=>$invited_id,
            'score'=>$score,
            'state'=>$state,
            'create_time'=>time()
        ]);
    }
    public static function bindParent($parent_id, $invited_id, $way = 0, $admin_id = 0, $state = 1)
    {
        $old_id = 0;
        $user = Db::name('user')->find($invited_id);
        $parent = Db::name('user')->find($parent_id);
        if ($user['yqr']) {
            $old_id = Db::name('user')->where(['yqm'=>$user['yqr']])->value('id');
            if ($old_id) {
                $record = Db::name('user_invite_record')->where(['user_id'=>$old_id, 'touserid'=>$invited_id, 'state'=>1])->find();
                $update = ['state'=>-1];
                if ($record['reward_get']==0) {
                    $update['reward_get'] = -1;
                }
                Db::name('user_invite_record')->where(['user_id'=>$old_id])->update($update);
            }
        }
        $config = Config::index(['in', ['invite']]);
        $reward = $config[$parent['sex']=='女'?'welfare_female':'welfare_male'];
        Db::name('user_invite_record')->insert([
            'user_id'=>$parent_id,
            'touserid'=>$invited_id,
            'old_touserid'=>$old_id,
            'way'=>$way,
            'state'=>$state,
            'reward'=>$reward,
            'admin_id'=>$admin_id,
            'create_time'=>time()
        ]);
        UserLevel::checkUserLevel($parent_id);

        if (strtotime($user['register_datetime'])>strtotime('-3 day')) {
            $result = Commission::afterBind($invited_id, $parent_id);
            if (is_array($result)) {
                if ($result['commission_chongzhi']) {
                    self::reward($invited_id, $result['chongzhi'], '金币充值奖励补发', 'topup');
                }
                if ($result['commission_huiyuan']) {
                    $money_rate = db('config_system')->where(['title'=>'money_rate'])->value('content');
                    self::reward($invited_id, $result['huiyuan'] * $money_rate, '会员充值奖励补发', 'topup');
                }
            }
        }
    }

    public static function rechargeWelfare($user)
    {
            return false;
        $user_id = $user['id'];
        $has = Db::name('recharge_welfare')->where(['user_id'=>$user_id])->find();
        if ($has) {
            return false;
        }
        $topup = UserData::where(['user_id'=>$user_id])->value('topup');
        if ($topup >= 3000) {
            $value = round($topup * 10 / 100, 2);
            $value = $value > 2000 ? 2000 : $value;
            $msg = "为了感谢你的使用，本平台特意赠送".$value."金币，在使用过程中谨防被骗，勿轻信他人，聊天之前请查看聊天手册";
            Db::startTrans();
            try{
                Balance::index($user_id, $value, $msg, 1);
                Db::name('recharge_welfare')->insert(['user_id'=>$user_id, 'recharge'=>$topup, 'value'=>$value, 'time'=>time()]);
                Privatechat::notice($user_id, $msg, '', 0, 0);
                Db::commit();    
            } catch (\Exception $e) {
                Db::rollback();
            }
        }
    }

    /**
 * 原有的女性用户分佣逻辑
 * 
 * @param int $user_id 用户ID
 * @param float $money 金额
 * @param string $msg 消息内容
 * @param string $channel 渠道类型
 * @param string $number 订单号
 * @param int $update 是否更新
 * @param float $show_income 显示金额
 * @param int $source_uid 源用户ID
 * @return bool
 */
public static function femaleRewardOld($user_id, $money, $msg, $channel = 'chat', $number = '', $update = 0, $show_income = 0, $source_uid = 0)
{
    $id = $user_id;
    $user = self::get($id);
    
    if (!$user || !$user['yqr']) {
        return false;
    }
    
    $config = Config::index('fencheng');
    
    // 获取邀请链
    for ($i = 1; $i <= 10; $i++) {
        $user = self::get($id);
        
        if ($user && $user['yqr'] && !$user['team_out']) {
            // 标记团队链存在的等级
            if ($user['level'] == 1) $childHasSuper = 1;
            if ($user['level'] == 2) $childHasYunying = 1;
            if ($user['level'] == 3) $childHasHehuo = 1;

            $parent = self::get(['yqm' => $user->yqr]);

            if (!$parent || $parent['delete_time'] > 0 || ($parent['is_banned'] && strtotime($parent['banned_end_time']) > time()) || ($parent->level!=3 && $user->level>=$parent->level)) {
                break;
            }

            $topup_commission = $config['shouyi_female_1'] * $money;
            $team_rate = $config['shouyi_chat_'.$parent['level']]??0;

            if ($childHasSuper) {
                $team_rate -= $config['shouyi_chat_1'];
            }
            if ($childHasYunying && $parent['level'] > 2) {
                $team_rate -= $config['shouyi_chat_1'];
            }
            $team_commission = $team_rate * $money;
            $levelText = '';
            if ($childHasHehuo) {
                $commission = ($topup_commission + $team_commission) * $config['shouyi_female_hehuo'];
                $levelText = '平级';
            } else {
                if ($i == 1) {
                    $commission = $topup_commission + $team_commission;
                } else {
                    $commission = $team_commission;
                    $levelText = '团队';
                }
            }

            $remark = $msg . " " . $levelText. "奖励";
            Income::index($parent->id, $id, $commission, $remark, 1, $number, 0, $update, 0, $source_uid);
        } else {
            break;
        }

        $id = $parent->id;
    }
    
    return true;
}
}
